// 引入axios
import axios from "axios";
import qs from 'qs'
import { showToast } from "vant";
import { useRouter } from "vue-router";
import store from '../store';

const router = useRouter();

const LOGOUT_CODE = 401 // token 过期
const SUCCESS_CODE = 1 // 成功
const ERROR_CODE = 0 // 成功

function reloadLogin() {
  // 登录失效, 去登录页
  showToast('登录失效，请重新登录!')
  setTimeout(() => {
    router.replace({
      path: "/login"
    });
  }, 1500)
}
// 判断是否是白名单接口(不需要token)
function getWhitelistFlag(requestUrl) {
  return ['api/user/login'].some(url => url.includes(requestUrl))
}
/** 
 *  @options { method: get/post..., query/data: {} }
 *  get请求参数放query里 post请求参数放data里
 */
export function request(urlObj, options = {}) {
  const token = localStorage.getItem('h5-token') || store.userInfo && store.userInfo.token
  let { url, method } = urlObj
  if (!token && getWhitelistFlag(url)) {
    reloadLogin()
    return
  }
  const { headers, data, query } = options;
  const requestParams = {};
  if (data) {
    requestParams.body = data;
  }
  requestParams.headers = {
    'Content-Type': 'multipart/form-data',
    ...headers,
    token
  };
  axios.defaults.baseURL = 'https://d-xueer.bigchun.com'
  const promise = new Promise((resolve, reject) => {
    if (['post', 'put'].includes(method)) {
      axios[method](url, requestParams.body, { headers: requestParams.headers }).then(response => {
        const { code } = response.data
        if (+code === LOGOUT_CODE) {
          // token失效
          reloadLogin()
          reject(e)
        } else {
          resolve(response.data || {})
        }
      }).catch(e => {
        reject(e)
      })
    } else if (['get', 'delete'].includes(method)) {
      url = `${url}?${qs.stringify(query)}`
      axios[method](url, requestParams).then(response => {

        const { code } = response.data
        if (+code === LOGOUT_CODE) {
          reloadLogin()
          reject(e)
        } else {
          resolve(response.data || {})
        }
      }).catch(e => {
        reject(e)
      })
    }
  });
  return promise;
}